from app import db, login_manager
from flask_login import UserMixin
import datetime
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey
from sqlalchemy.orm import relationship

@login_manager.user_loader
def load_user(user_id):
    # 判断是教师还是学生
    if user_id.startswith('t'):
        return Teacher.query.get(int(user_id[1:]))
    else:
        return Student.query.get(int(user_id[1:]))

class Teacher(db.Model, UserMixin):
    """教师表"""
    __tablename__ = 'teachers'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), nullable=False)
    email = Column(String(100), unique=True)
    password = Column(String(100), nullable=False)
    subject = Column(String(50))
    created_at = Column(DateTime, default=datetime.datetime.now)
    
    # 建立与学生的一对多关系
    students = relationship("Student", back_populates="teacher")
    
    def __repr__(self):
        return f"<Teacher(id={self.id}, name='{self.name}', subject='{self.subject}')>"
    
    def get_id(self):
        # 为了区分教师和学生，给教师ID加前缀't'
        return f"t{self.id}"


class Student(db.Model, UserMixin):
    """学生表"""
    __tablename__ = 'students'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), nullable=False)
    email = Column(String(100), unique=True)
    password = Column(String(100), nullable=False)
    grade = Column(String(20))  # 年级
    created_at = Column(DateTime, default=datetime.datetime.now)
    
    # 一个学生只能有一名教师，多对一关系
    teacher_id = Column(Integer, ForeignKey('teachers.id'), nullable=False)
    teacher = relationship("Teacher", back_populates="students")
    
    # 建立与成绩的一对多关系
    scores = relationship("Score", back_populates="student")
    
    def __repr__(self):
        return f"<Student(id={self.id}, name='{self.name}', grade='{self.grade}')>"
    
    def get_id(self):
        # 为了区分教师和学生，给学生ID加前缀's'
        return f"s{self.id}"


class Course(db.Model):
    """课程表"""
    __tablename__ = 'courses'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), nullable=False)
    description = Column(String(200))
    
    # 建立与成绩的一对多关系
    scores = relationship("Score", back_populates="course")
    
    def __repr__(self):
        return f"<Course(id={self.id}, name='{self.name}')>"


class Score(db.Model):
    """成绩表 - 存储学生的课程成绩"""
    __tablename__ = 'scores'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    student_id = Column(Integer, ForeignKey('students.id'), nullable=False)
    course_id = Column(Integer, ForeignKey('courses.id'), nullable=False)
    score_value = Column(Float, nullable=False)
    test_number = Column(Integer, nullable=False)  # 第几次考试，取值1-10
    test_date = Column(DateTime, default=datetime.datetime.now)
    
    # 建立多对一关系
    student = relationship("Student", back_populates="scores")
    course = relationship("Course", back_populates="scores")
    
    def __repr__(self):
        return f"<Score(student_id={self.student_id}, course_id={self.course_id}, test_number={self.test_number}, score={self.score_value})>" 